﻿/*========================== 
 * @author 郑金泉
 * @desc Excel文档类
 * ========================= */
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

using NPOI;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;

namespace Obsidian.Data.Excel
{
    public class Workbook
    {

        private HSSFWorkbook workbook;
        private Dictionary<string, Sheet> dictSheets = new Dictionary<string, Sheet>();

        public Workbook() 
        {
            workbook = new HSSFWorkbook();
        }

        public Workbook(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            workbook = new HSSFWorkbook(fs);
        }

        public Sheet GetSheet(string name)
        {
            if (dictSheets.ContainsKey(name))
                return dictSheets[name];

            NPOI.SS.UserModel.Sheet npoiSheet = workbook.GetSheet(name);
            if (npoiSheet == null)
                throw new Exception("名为" + name + "的sheet不存在");
            Sheet sheet = new Sheet(npoiSheet);
            dictSheets.Add(name, sheet);
            return sheet;

        }

        public Sheet GetSheet(int i)
        {
            NPOI.SS.UserModel.Sheet npoiSheet = workbook.GetSheetAt(i);

            if (npoiSheet == null)
                throw new Exception("sheet不存在");
            string sheetName = npoiSheet.SheetName;
            if (dictSheets.ContainsKey(sheetName))
            {
                return dictSheets[sheetName];
            }
            else
            {
                Sheet sheet = new Sheet(npoiSheet);
                dictSheets.Add(sheetName, sheet);
                return sheet;
            }
        }

        public Sheet CreateSheet(string name)
        {
            if (dictSheets.ContainsKey(name))
                throw new Exception("已经存在名称为" + name + "的sheet");
            NPOI.SS.UserModel.Sheet npoiSheet = workbook.CreateSheet(name);
            Sheet sheet = new Sheet(npoiSheet);
            dictSheets.Add(name, sheet);
            return sheet;
        }

        public Sheet[] GetSheets()
        {
            int i=0;
            int len = workbook.NumberOfSheets;
            Sheet[] sheets = new Sheet[len];
            for (; i < len; i++)
                sheets[i] = this.GetSheet(i);
            return sheets;
        }

        public void Save(string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                this.workbook.Write(fs);
            }
        }

    }
}
